package com.friday.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.friday.bean.Company;
import com.friday.dao.AgentDao;
import com.friday.dao.CompanyDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CompanyController {

    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private AgentDao agentDao;

    @RequestMapping("/company")
    public JSONObject getCompanyById(@RequestParam("id") int id){
        return companyDao.getCompanyById(id);
    }

    @RequestMapping("/companyList")
    public JSONArray getAllCompany(){
        return companyDao.getAllCompany();
    }

    @RequestMapping("/companyEdit")
    public String editCompany(@RequestBody JSONObject message){
        int tag = companyDao.editCompanyById(message);
        if(tag>0){
            return "success";
        }else{
            return "fail";
        }
    }

    @RequestMapping("/companyAdd")
    public JSONObject addCompany(@RequestBody JSONObject message){
        JSONObject result = new JSONObject();
        int tag = companyDao.addCompany(message);
        if( tag>0 ){
            result.put("result","success");
            result.put("company_id",message.getInteger("id"));
        }else {
            result.put("result","fail");
            result.put("company_id",null);
        }
        return result;
    }

    @RequestMapping("/companyDelete")
    public String delCompany(@RequestParam("id") int id){
        //删除公司及对应代理人
        int tag1 = companyDao.delCompanyById(id);
        int tag2 = agentDao.delAgentByCompany(id);
        if(tag1 >0){
            return "success";
        }else{
            return "fail";
        }
    }

    @RequestMapping("/matchCompanyList")
    public JSONArray getMatchCompany(@RequestParam("id") int id,@RequestParam("authority") String authority){
        return companyDao.getMatchCompany(id, authority);
    }
}
